import Vue from "vue";
import store from "@/store/index";
import VueRouter from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css"; // progress bar style
import { Message } from "element-ui";

NProgress.configure({ showSpinner: false });

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "hash",
  routes: [
    {
      path: "/",
      name: "home",
      meta: { isPublic: true },
      component: () => import(/* webpackChunkName: "home" */ "@/views/home/index.vue"),
    },
    {
      // 登录
      path: "/login",
      name: "login",
      meta: { isPublic: true },
      component: () => import(/* webpackChunkName: "login" */ "@/views/login/index.vue"),
    },
    {
      // 注册
      path: "/register",
      name: "register",
      meta: { isPublic: true },
      component: () => import(/* webpackChunkName: "register" */ "@/views/register/index.vue"),
    },
    {
      // 项目列表页
      path: "/projects",
      name: "projects",
      component: () => import(/* webpackChunkName: "projects" */ "@/views/projects/index.vue"),
    },
    {
      // 项目设置页面
      path: "/project/settings/:projectid",
      name: "projectSettings",
      component: () => import(/* webpackChunkName: "projectSettings" */ "@/views/projects/settings.vue"),
    },
    {
      // 创建项目页
      path: "/project/create",
      name: "createProject",
      component: () => import(/* webpackChunkName: "createProjects" */ "@/views/projects/create.vue"),
    },
    {
      // 文档目录列表页
      path: "/:projectid/docs",
      name: "docs",
      component: () => import(/* webpackChunkName: "docs" */ "@/views/docs/index.vue"),
      children: [
        {
          // 文档详情页 docid: 文档ID
          path: "/:projectid/docs/:docid",
          name: "docsDetail",
          component: () => import(/* webpackChunkName: "docsDetail" */ "@/views/docs/detail.vue"),
        },
      ],
    },
    {
      // 创建文档页 projectid: 项目ID, 注: 此处path不能是/:projectid/docs/create, 会匹配到文档详情页, 把create当成docid
      path: "/:projectid/create/docs",
      name: "createDocs",
      component: () => import(/* webpackChunkName: "createDocs" */ "@/views/docs/create.vue"),
    },
  ],
});

router.beforeEach((to, $from, next) => {
  NProgress.start();

  // 不需要登录
  if (to.meta.isPublic) {
    return next();
  }

  // 是否登录
  const isLogin = store.getters["user/isLogin"];
  if (!isLogin) {
    NProgress.done();
    Message.error("请先登录");
    return router.replace({ name: "login" });
  }

  return next();
});

router.afterEach(() => NProgress.done());

export default router;
